/**
 * 传输管理页面逻辑
 */

const log = require('electron-log');
const {
  showNotification,
  formatFileSize,
  formatSpeed,
  formatDate,
  setupWindowControls,
  navigateToPage,
  getUserData
} = require('../utils/common');

// 传输任务数据（从localStorage加载或使用示例数据）
let transferTasks = [];
let currentFilter = 'all';

// 页面初始化
window.addEventListener('DOMContentLoaded', () => {
  // 检查登录状态
  const userData = getUserData();
  if (!userData) {
    navigateToPage('login');
    return;
  }

  // 设置窗口控制
  setupWindowControls();

  // 绑定事件
  bindEvents();

  // 加载传输任务
  loadTransferTasks();

  // 定时刷新
  setInterval(updateUI, 1000);

  log.info('传输管理页面初始化完成');
});

// 绑定事件
function bindEvents() {
  // 按钮事件
  document.getElementById('back-btn')?.addEventListener('click', () => {
    navigateToPage('main');
  });

  document.getElementById('pause-all-btn')?.addEventListener('click', pauseAllTasks);
  document.getElementById('resume-all-btn')?.addEventListener('click', resumeAllTasks);
  document.getElementById('clear-completed-btn')?.addEventListener('click', clearCompletedTasks);

  // 筛选按钮
  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      currentFilter = btn.dataset.filter;
      
      // 更新按钮状态
      document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      
      // 重新渲染列表
      renderTransferList();
    });
  });
}

// 加载传输任务
function loadTransferTasks() {
  const saved = localStorage.getItem('transferTasks');
  if (saved) {
    try {
      transferTasks = JSON.parse(saved);
    } catch (error) {
      log.error('加载传输任务失败:', error);
      transferTasks = [];
    }
  }

  // 如果没有任务，添加一些示例任务
  if (transferTasks.length === 0) {
    transferTasks = getSampleTasks();
    saveTransferTasks();
  }

  updateUI();
}

// 保存传输任务
function saveTransferTasks() {
  localStorage.setItem('transferTasks', JSON.stringify(transferTasks));
}

// 更新UI
function updateUI() {
  updateStats();
  renderTransferList();
}

// 更新统计信息
function updateStats() {
  const uploadTasks = transferTasks.filter(t => t.type === 'upload' && (t.status === 'uploading' || t.status === 'paused'));
  const downloadTasks = transferTasks.filter(t => t.type === 'download' && (t.status === 'downloading' || t.status === 'paused'));
  const completedTasks = transferTasks.filter(t => t.status === 'completed');
  const failedTasks = transferTasks.filter(t => t.status === 'failed');
  
  const activeTasks = transferTasks.filter(t => t.status === 'uploading' || t.status === 'downloading');
  const avgSpeed = activeTasks.length > 0 
    ? activeTasks.reduce((sum, t) => sum + (t.speed || 0), 0) / activeTasks.length 
    : 0;

  document.getElementById('upload-count').textContent = uploadTasks.length;
  document.getElementById('download-count').textContent = downloadTasks.length;
  document.getElementById('completed-count').textContent = completedTasks.length;
  document.getElementById('failed-count').textContent = failedTasks.length;
  document.getElementById('avg-speed').textContent = formatSpeed(avgSpeed);
}

// 渲染传输列表
function renderTransferList() {
  const container = document.getElementById('transfer-list');
  if (!container) return;

  // 筛选任务
  let filtered = transferTasks;
  if (currentFilter !== 'all') {
    filtered = transferTasks.filter(t => t.status === currentFilter);
  }

  // 如果没有任务
  if (filtered.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <div class="empty-state-icon">📊</div>
        <div class="empty-state-text">暂无传输任务</div>
      </div>
    `;
    return;
  }

  // 渲染任务项
  container.innerHTML = '';
  filtered.forEach(task => {
    const item = createTaskItem(task);
    container.appendChild(item);
  });
}

// 创建任务项
function createTaskItem(task) {
  const item = document.createElement('div');
  item.className = 'transfer-task-item';

  const typeLabel = task.type === 'upload' ? '上传' : '下载';
  const statusLabel = getStatusLabel(task.status);
  const progressClass = task.status === 'completed' ? 'completed' : 
                       task.status === 'failed' ? 'failed' :
                       task.status === 'paused' ? 'paused' : '';

  item.innerHTML = `
    <div class="transfer-task-header">
      <div class="transfer-task-info">
        <div class="transfer-task-name">
          <span class="transfer-task-type ${task.type}">${typeLabel}</span>
          ${task.fileName}
        </div>
        <div class="transfer-task-path">${task.filePath || task.remotePath || ''}</div>
      </div>
      <div class="transfer-task-actions">
        ${task.status === 'uploading' || task.status === 'downloading' ? 
          `<button class="task-action-btn" data-action="pause" data-id="${task.id}" title="暂停">⏸️</button>` : ''}
        ${task.status === 'paused' ? 
          `<button class="task-action-btn" data-action="resume" data-id="${task.id}" title="继续">▶️</button>` : ''}
        ${task.status === 'failed' ? 
          `<button class="task-action-btn" data-action="retry" data-id="${task.id}" title="重试">🔄</button>` : ''}
        <button class="task-action-btn" data-action="delete" data-id="${task.id}" title="删除">🗑️</button>
      </div>
    </div>
    <div class="transfer-task-progress">
      <div class="progress-bar">
        <div class="progress-fill ${progressClass}" style="width: ${task.progress || 0}%"></div>
      </div>
      <div class="progress-info">
        <span>${task.progress || 0}%</span>
        <span>${task.speed ? formatSpeed(task.speed) : '0 B/s'}</span>
      </div>
    </div>
    <div class="transfer-task-meta">
      <div class="meta-item">
        <span>大小: ${formatFileSize(task.fileSize || 0)}</span>
        <span class="status-badge ${task.status}">${statusLabel}</span>
      </div>
      <div class="meta-item">
        <span>${task.startTime ? formatDate(task.startTime) : ''}</span>
      </div>
    </div>
  `;

  // 绑定按钮事件
  item.querySelectorAll('.task-action-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const action = btn.dataset.action;
      const id = btn.dataset.id;
      
      handleTaskAction(action, id);
    });
  });

  return item;
}

// 获取状态标签
function getStatusLabel(status) {
  const labels = {
    uploading: '上传中',
    downloading: '下载中',
    paused: '已暂停',
    completed: '已完成',
    failed: '失败'
  };
  return labels[status] || status;
}

// 处理任务操作
function handleTaskAction(action, taskId) {
  const task = transferTasks.find(t => t.id === taskId);
  if (!task) return;

  switch (action) {
    case 'pause':
      pauseTask(taskId);
      break;
    case 'resume':
      resumeTask(taskId);
      break;
    case 'retry':
      retryTask(taskId);
      break;
    case 'delete':
      deleteTask(taskId);
      break;
  }
}

// 暂停任务
function pauseTask(taskId) {
  const task = transferTasks.find(t => t.id === taskId);
  if (task) {
    task.status = 'paused';
    saveTransferTasks();
    updateUI();
    showNotification(`已暂停: ${task.fileName}`, 'info');
    log.info(`暂停任务: ${task.fileName}`);
  }
}

// 继续任务
function resumeTask(taskId) {
  const task = transferTasks.find(t => t.id === taskId);
  if (task) {
    task.status = task.type === 'upload' ? 'uploading' : 'downloading';
    saveTransferTasks();
    updateUI();
    showNotification(`已继续: ${task.fileName}`, 'info');
    log.info(`继续任务: ${task.fileName}`);
  }
}

// 重试任务
function retryTask(taskId) {
  const task = transferTasks.find(t => t.id === taskId);
  if (task) {
    task.status = task.type === 'upload' ? 'uploading' : 'downloading';
    task.progress = 0;
    task.error = null;
    saveTransferTasks();
    updateUI();
    showNotification(`正在重试: ${task.fileName}`, 'info');
    log.info(`重试任务: ${task.fileName}`);
  }
}

// 删除任务
function deleteTask(taskId) {
  const task = transferTasks.find(t => t.id === taskId);
  if (task && confirm(`确定要删除任务 "${task.fileName}" 吗？`)) {
    transferTasks = transferTasks.filter(t => t.id !== taskId);
    saveTransferTasks();
    updateUI();
    showNotification('任务已删除', 'info');
    log.info(`删除任务: ${task.fileName}`);
  }
}

// 暂停所有任务
function pauseAllTasks() {
  let count = 0;
  transferTasks.forEach(task => {
    if (task.status === 'uploading' || task.status === 'downloading') {
      task.status = 'paused';
      count++;
    }
  });
  
  if (count > 0) {
    saveTransferTasks();
    updateUI();
    showNotification(`已暂停 ${count} 个任务`, 'info');
  } else {
    showNotification('没有正在进行的任务', 'warning');
  }
}

// 继续所有任务
function resumeAllTasks() {
  let count = 0;
  transferTasks.forEach(task => {
    if (task.status === 'paused') {
      task.status = task.type === 'upload' ? 'uploading' : 'downloading';
      count++;
    }
  });
  
  if (count > 0) {
    saveTransferTasks();
    updateUI();
    showNotification(`已继续 ${count} 个任务`, 'info');
  } else {
    showNotification('没有已暂停的任务', 'warning');
  }
}

// 清除已完成任务
function clearCompletedTasks() {
  const completedCount = transferTasks.filter(t => t.status === 'completed').length;
  
  if (completedCount === 0) {
    showNotification('没有已完成的任务', 'warning');
    return;
  }
  
  if (confirm(`确定要清除 ${completedCount} 个已完成的任务吗？`)) {
    transferTasks = transferTasks.filter(t => t.status !== 'completed');
    saveTransferTasks();
    updateUI();
    showNotification(`已清除 ${completedCount} 个已完成任务`, 'success');
  }
}

// 获取示例任务
function getSampleTasks() {
  const now = new Date();
  return [
    {
      id: '1',
      type: 'upload',
      fileName: 'report.pdf',
      filePath: '/Documents/report.pdf',
      remotePath: '/uploads/report.pdf',
      fileSize: 2.5 * 1024 * 1024,
      progress: 100,
      speed: 0,
      status: 'completed',
      startTime: new Date(now.getTime() - 300000).toISOString()
    },
    {
      id: '2',
      type: 'download',
      fileName: 'presentation.pptx',
      filePath: '/Downloads/presentation.pptx',
      remotePath: '/files/presentation.pptx',
      fileSize: 15 * 1024 * 1024,
      progress: 65,
      speed: 1.2 * 1024 * 1024,
      status: 'downloading',
      startTime: new Date(now.getTime() - 120000).toISOString()
    },
    {
      id: '3',
      type: 'upload',
      fileName: 'image.jpg',
      filePath: '/Pictures/image.jpg',
      remotePath: '/uploads/image.jpg',
      fileSize: 3.2 * 1024 * 1024,
      progress: 45,
      speed: 800 * 1024,
      status: 'paused',
      startTime: new Date(now.getTime() - 180000).toISOString()
    },
    {
      id: '4',
      type: 'upload',
      fileName: 'video.mp4',
      filePath: '/Videos/video.mp4',
      remotePath: '/uploads/video.mp4',
      fileSize: 50 * 1024 * 1024,
      progress: 20,
      speed: 0,
      status: 'failed',
      error: '网络连接中断',
      startTime: new Date(now.getTime() - 600000).toISOString()
    }
  ];
}
